package mww.servlet;

import java.io.IOException;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import javassist.bytecode.Descriptor.Iterator;
import mww.common.DaoException;
import mww.common.Page;
import mww.common.ServiceException;
import mww.javabean.entity.Student;
import mww.javabean.entity.StudentC;
import mww.javabean.entity.TeacherC;
import mww.javabean.entity.User;
import mww.javabean.service.StudentCService;
import mww.javabean.service.StudentCServiceImpl;
import mww.javabean.service.StudentService;
import mww.javabean.service.StudentServiceImpl;
import mww.javabean.service.TeacherCService;
import mww.javabean.service.TeacherCServiceImpl;

public class StudentCServlet extends HttpServlet {
	TeacherCService tcService = new TeacherCServiceImpl();
	StudentCService scService = new StudentCServiceImpl();
	StudentService stuService = new StudentServiceImpl();

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		HttpServletRequest req = (HttpServletRequest) request;// 将request强制转换为HttpServletRequest类型
		HttpServletResponse res = (HttpServletResponse) response;// 将response强制转换为HttpServletResponse类型
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String action = request.getParameter("action");
		if (action.equals("listTeacherC")) {
			doListTeacherC(request, response);
		} else if (action.equals("checkTeacherC")) {
			doCheckTeacherC(request, response);
		} else if (action.equals("addStudentC")) {
			doAddStudentC(request, response);
		} else if (action.equals("showStudentC")) {
			doShowStudentC(request, response);
		} else if (action.equals("delStudentC")) {
			doDeleteStudentC(request, response);
		} else if (action.equals("checkStudentC")) {
			doCheckStudentC(request, response);
		} else if (action.equals("otherStudentShow")) {
			doShowOtherStudent(request, response);
		} else if (action.equals("listSchedule")) {
			doListSchedule(request, response);
		} else if (action.equals("changePwd")) {
			doChangePwd(request, response);
		} else {
			session.setAttribute("message", "错误访问，请重新登录");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}

	private void doListTeacherC(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int curPage = 1;
		String temp = request.getParameter("curPage");
		if (temp != null) {
			curPage = Integer.parseInt(request.getParameter("curPage"));
		}
		try {
			Map map = tcService.findAllTeacherC(curPage);
			ArrayList list = (ArrayList) map.get("list");
			Page pa = (Page) map.get("pa");
			request.setAttribute("curPage", pa.getCurPage());// 向显示页传递当前页页码
			request.setAttribute("pageCount", pa.getPageCount());// 向显示页传递总页数
			request.setAttribute("list", list);// 向显示页传递结果集
			request.getRequestDispatcher("/student/studentCList.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	private void doCheckTeacherC(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		TeacherCService tcService = new TeacherCServiceImpl();
		// 从request从取出查询条件
		String courseNo = request.getParameter("courseNo");
		String courseName = request.getParameter("courseName");
		String teacherName = request.getParameter("teacherName");
		String tcTime1 = request.getParameter("tcTime1");
		String tcTime2 = request.getParameter("tcTime2");
		int tcTeacherNo = 0;
		String tcTeacherNoTemp = request.getParameter("tcTeacherNo");
		if (tcTeacherNoTemp != null && !tcTeacherNoTemp.equals("")) {
			tcTeacherNo = Integer.parseInt(tcTeacherNoTemp);
		}

		float credit = 0;
		String creditTemp = request.getParameter("credit");
		if (creditTemp != null && !creditTemp.equals("")) {
			credit = Float.parseFloat(creditTemp);
		}

		// 将查询条件传回jsp页面
		request.setAttribute("courseNo", courseNo);
		request.setAttribute("courseName", courseName);
		request.setAttribute("tcTeacherNo", tcTeacherNo);
		request.setAttribute("teacherName", teacherName);
		request.setAttribute("credit", credit);
		request.setAttribute("tcTime1", tcTime1);
		request.setAttribute("tcTime2", tcTime2);

		String tcTime = "";
		// 上课时间 组合为（星期-节次）
		if (!tcTime1.equals("0") && !tcTime2.equals("0")) { // 星期和节次均限制
			tcTime = tcTime1 + "-" + tcTime2;
		} else if (!tcTime1.equals("0") && tcTime2.equals("0")) { // 限制星期，不限节次
			tcTime = tcTime1 + "-";
		} else if (tcTime1.equals("0") && !tcTime2.equals("0")) { // 限制节次，不限星期
			tcTime = "-" + tcTime2;
		} else { // 星期、节次均未限制
			tcTime = "";
		}

		int curPage = 1;
		String temp = request.getParameter("curPage");
		if (temp != null) {
			curPage = Integer.parseInt(request.getParameter("curPage"));
		}
		try {
			TeacherC con = new TeacherC();
			con.setCourseNo(courseNo);
			con.setCourseName(courseName);
			con.setTcTime(tcTime);
			con.setTcTeacherNo(tcTeacherNo);
			con.setTeacherName(teacherName);
			con.setCredit(credit);
			Map map = tcService.findAllTeacherCByMostCon(con, curPage);
			ArrayList list = (ArrayList) map.get("list");
			Page pa = (Page) map.get("pa");
			request.setAttribute("curPage", pa.getCurPage());// 向显示页传递当前页页码
			request.setAttribute("pageCount", pa.getPageCount());// 向显示页传递总页数
			request.setAttribute("list", list);// 向显示页传递结果集
			request.getRequestDispatcher("/student/studentCList.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	private void doAddStudentC(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		String studentNo = ((User) session.getAttribute("user")).getLoginName();
		String studentName = ((User) session.getAttribute("user")).getName();
		String courseNo = request.getParameter("courseNo");
		String teacherNo = request.getParameter("teacherNo");

		int tcTeacherNo = 0;
		String tcTeacherNoTemp = request.getParameter("tcTeacherNo");
		if (null != tcTeacherNoTemp && !tcTeacherNoTemp.equals("")) {
			tcTeacherNo = Integer.parseInt(request.getParameter("tcTeacherNo"));
		}
		
		try {
			TeacherC tc = tcService.findTeacherCById(teacherNo, courseNo, tcTeacherNo);
			
			StudentC sc = new StudentC();
			sc.setStudentNo(studentNo);
			sc.setStudentName(studentName);
			sc.setCourseNo(courseNo);
			sc.setCourseName(tc.getCourseName());
			sc.setTeacherNo(teacherNo);
			sc.setTcTeacherNo(tcTeacherNo);
			sc.setCredit(tc.getCredit());
			// 检测冲突
			if (scService.checkConflict(studentNo, tc.getTcTime())) {
				session.setAttribute("message", "与已选课程冲突");
				request.getRequestDispatcher("/student/scServlet?action=listTeacherC").forward(request, response);
			}
			else {
				if(tcService.isFull(teacherNo, courseNo, tcTeacherNo)){//当前选课人数已满
					session.setAttribute("message", "当前选课人数已满");
				}else{
					scService.addStudentC(sc);
					session.setAttribute("message", "选课成功");
					tcService.incTcSel(teacherNo, courseNo, tcTeacherNo);
				}
				request.getRequestDispatcher("/student/scServlet?action=listTeacherC").forward(request, response);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	private void doDeleteStudentC(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		String studentNo = ((User) session.getAttribute("user")).getLoginName();
		String courseNo = request.getParameter("courseNo");
		String teacherNo = request.getParameter("teacherNo");

		int tcTeacherNo = 0;
		String tcTeacherNoTemp = request.getParameter("tcTeacherNo");
		if (null != tcTeacherNoTemp && !tcTeacherNoTemp.equals("")) {
			tcTeacherNo = Integer.parseInt(request.getParameter("tcTeacherNo"));
		}

		try {
			scService.delStudentCById(studentNo,teacherNo, courseNo,tcTeacherNo );
			tcService.decTcSel(teacherNo, courseNo, tcTeacherNo);
			session.setAttribute("message", "退课成功");
			// 删除成功后刷新显示课表
			ArrayList list = (ArrayList) scService.findAllCourseByStudentNo(studentNo);
			request.setAttribute("list", convertSchdule(list));// 向显示页传递结果集
			request.getRequestDispatcher("/student/studentSchedule.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	private void doChangePwd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		StudentService stuService = new StudentServiceImpl();
		String loginName = ((User) session.getAttribute("user")).getLoginName();
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword1");
		try {
			Student student = stuService.findStudentByStudentNo(loginName);
			if (!student.getPassword().equals(oldPassword)) { // 若输入密码不吻合
				session.setAttribute("message", "原密码与账号不匹配");
			} else if (student.getPassword().equals(newPassword)) { // 若密码与账号吻合，则更改密码
				session.setAttribute("message", "原密码与新密码不能相同");
				request.getRequestDispatcher("/student/changePwd.jsp").forward(request, response);
			} else {
				stuService.updateStudentPwd(loginName, newPassword);
				session.setAttribute("message", "修改成功");
				request.getRequestDispatcher("/student/changePwd.jsp").forward(request, response);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	private void doListSchedule(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		String studentNo = ((User) session.getAttribute("user")).getLoginName();
		try {
			ArrayList list = (ArrayList) scService.findAllCourseByStudentNo(studentNo);

			request.setAttribute("list", convertSchdule(list));// 向显示页传递结果集
			request.getRequestDispatcher("/student/studentSchedule.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	private void doShowStudentC(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();// 获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
		String studentNo = ((User) session.getAttribute("user")).getLoginName();
		try {
			Student st = stuService.findStudentByStudentNo(studentNo);
			ArrayList list = (ArrayList) scService.findStudentCByStudentNo(studentNo);
			request.setAttribute("student", st);
			request.setAttribute("list", list);// 向显示页传递结果集
			request.getRequestDispatcher("/student/studentShow.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	private void doCheckStudentC(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 从request从取出查询条件
		String studentNo = request.getParameter("studentNo");
		String studentClass = request.getParameter("studentClass");
		String studentMajor = request.getParameter("studentMajor");

		// 将查询条件传回jsp页面
		request.setAttribute("studentNo", studentNo);
		request.setAttribute("studentClass", studentClass);
		request.setAttribute("studentMajor", studentMajor);

		int curPage = 1;
		String temp = request.getParameter("curPage");
		if (temp != null) {
			curPage = Integer.parseInt(request.getParameter("curPage"));
		}
		try {
			Student condition = new Student();
			condition.setStudentNo(studentNo);
			condition.setStudentClass(studentClass);
			condition.setStudentMajor(studentMajor);
			// 根据学号、班级、专业，模糊查询所有学生
			Map map = stuService.findAllStudentByMostCon(condition, curPage);
			ArrayList list = (ArrayList) map.get("list");
			Page pa = (Page) map.get("pa");
			request.setAttribute("curPage", pa.getCurPage());// 向显示页传递当前页页码
			request.setAttribute("pageCount", pa.getPageCount());// 向显示页传递总页数
			request.setAttribute("list", list);// 向显示页传递结果集
			request.getRequestDispatcher("/student/studentCheck.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	private void doShowOtherStudent(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String studentNo = request.getParameter("studentNo");

		try {
			ArrayList list = (ArrayList) scService.findStudentCByStudentNo(studentNo);
			Student student = new StudentServiceImpl().findStudentByStudentNo(studentNo);
			request.setAttribute("student", student); // 向显示页传递学生信息
			request.setAttribute("list", list);// 向显示页传递结果集
			request.getRequestDispatcher("/student/otherStudentShow.jsp").forward(request, response);
		} catch (ServiceException e) {
			e.printStackTrace();
			request.setAttribute("se", e);
			request.getRequestDispatcher("/serviceException.jsp").forward(request, response);
		} catch (DaoException e) {
			e.printStackTrace();
			request.setAttribute("de", e);
			request.getRequestDispatcher("/daoException.jsp").forward(request, response);
		}
	}

	public List convertSchdule(List list) {
		TeacherC tc = new TeacherC();
		int n = list.size();
		ArrayList newlist = new ArrayList();
		while (n-- > 0) {
			tc = (TeacherC) list.get(n);
			for (int j = 0; j < 6; j++) {
				for (int k = 0; k < 7; k++) {
					if (tc.getTcTime().equals(k + "-" + j))
						// 吧时间星期-节次，转化为星期节次 3-1 --->31
						tc.setTcTime(String.valueOf(k) + String.valueOf(j));
				}
			}
			newlist.add(tc);
		}
		return newlist;
	}
}
